
namespace ShoppingCart.WebSite.Code
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Diagnostics;
    using System.Globalization;
    using System.Linq;
    using System.Net.Mail;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using Business.Logic;
    using SC = Business.Entity;

    public class BasePage : Page
    {
        protected string Step
        {
            get { return Session["Step"] == null ? string.Empty : Session["Step"].ToString(); }
            set { Session["Step"] = value; }
        }

        protected int IdCliente
        {
            get
            {
                if (User.Identity.IsAuthenticated)
                {
                    if (User.IsInRole("Cliente") && Session["IdCliente"] == null)
                    {
                        var user = Membership.GetUser();
                        var cliente = ClienteManager.Instancia.ObtenerPorGuid((Guid)user.ProviderUserKey);
                        Session["IdCliente"] = cliente.IdCliente;
                    }
                }
                return Session["IdCliente"] == null ? 0 : Convert.ToInt32(Session["IdCliente"]);
            }
            set { Session["IdCliente"] = value; }
        }

        protected int IdDepartamento
        {
            get { return Session["IdDepartamento"] == null ? 0 : Convert.ToInt32(Session["IdDepartamento"]); }
            set { Session["IdDepartamento"] = value; }
        }

        protected List<SC.Producto> Carrito 
        { 
            get { return Session["Carrito"] == null ? new List<SC.Producto>() : (List<SC.Producto>)Session["Carrito"]; }
            set
            {
                Session["Carrito"] = value;
                InvokeUpdateCarrito(EventArgs.Empty);
            }
        }

        protected BaseMasterPage MasterPage
        {
            get { return Master as BaseMasterPage; }
        }

        public event EventHandler UpdateCarrito;

        protected void InvokeUpdateCarrito(EventArgs e)
        {
            if (UpdateCarrito != null) UpdateCarrito(this, e);
        }

        protected void AddProducto(SC.Producto producto)
        {
            var carrito = Carrito;
            var productito = carrito.Where(p => p.IdProducto == producto.IdProducto).FirstOrDefault();
            if (productito != null) productito.Cantidad = producto.Cantidad;
            else carrito.Add(producto);
            Carrito = carrito;
        }

        protected void RemoveProducto(int idProducto)
        {
            var carrito = Carrito;
            carrito.RemoveAll(p => p.IdProducto == idProducto);
            Carrito = carrito;
        }

        protected override void OnInit(EventArgs e)
        {
            if (string.IsNullOrEmpty(Title) ||
                string.Compare(Title, "Untitled Page") == 0 ||
                string.Compare(Title, "Sin Titulo") == 0)
            {
                Title = GetNamePage() + @" | " + ConfigurationManager.AppSettings["WebSite"];
            }
            base.OnInit(e);
        }

        protected string GetNamePage()
        {
            var root = HttpContext.Current.Request.RawUrl.Split('/');
            var name = (root[root.GetUpperBound(0)] == "") ? root[root.GetUpperBound(0) - 1] : root[root.GetUpperBound(0)];
            root = name.Split('?');
            name = root[0];
            root = name.Split('.');
            name = root[0];
            return (name.Substring(0, 1).ToUpperInvariant()) + name.Substring(1, name.Length - 1);
        }

        protected string GetMessage(string content, MessageType type)
        {
            return string.Format(@"<div class=""message {0}""><p>{1}</p></div>", type, content);
        }

        protected DateTime GetCurrentDatetime(string datetime)
        {
            IFormatProvider format = new CultureInfo("es-ES", true);
            return DateTime.Parse(datetime, format, DateTimeStyles.NoCurrentDateDefault);
        }

        protected string RemoveHtmlTags(string content, int lenght)
        {
            var text = Regex.Replace(content, @"\<[^\>]*\>", "");
            if (lenght > 3 && lenght < text.Length)
                if (lenght - 3 < text.Length)
                    return text.Substring(0, lenght - 3) + "...";
            return text;
        }

        protected bool SendEmail(string address, string subject, string body)
        {
            var result = false;
            var message = new MailMessage();

            message.To.Add(address);
            message.Subject = subject;
            message.SubjectEncoding = Encoding.UTF8;
            message.Body = body;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;
            message.Priority = MailPriority.Normal;

            try
            {
                var smtp = new SmtpClient {EnableSsl = true};
                smtp.Send(message);
                result = true;
            }
            catch (SmtpException ex)
            {
                Debug.Write(ex.Message);
            }
            finally
            {
                message.Dispose();
            }
            return result;
        }

        protected void SaveImage(string path, HttpPostedFile file)
        {
            using (var originalImage = System.Drawing.Image.FromStream(file.InputStream))
            {
                using (var resizedImage = originalImage.GetThumbnailImage(originalImage.Width/2, originalImage.Height/2, null, IntPtr.Zero))
                {
                    resizedImage.Save(path);
                }
            }
        }

        protected decimal CurrencyToDecimal(string value)
        {
            if (value.Length == 0) return 0;
            return Decimal.Parse(value.Replace(" ", ""),
                                 NumberStyles.Any |
                                 NumberStyles.AllowCurrencySymbol |
                                 NumberStyles.AllowThousands |
                                 NumberStyles.AllowDecimalPoint);
        }

        protected enum MessageType
        {
            errormsg,
            success,
            info,
            warning
        }
    }
}
